﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace DongFangGuoKai.WMSPlatform.Commn.Tools
{
    public static class EnumTool
    {

        /// <summary>
        /// 获取字段Description
        /// </summary>
        /// <param name="fieldInfo">FieldInfo</param>
        /// <returns>DescriptionAttribute[]</returns>
        public static DescriptionAttribute[] GetDescriptAttr(this FieldInfo fieldInfo)
        {
            if (fieldInfo != null)
            {
                return (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            }
            return null;
        }  


        /// <summary>
        /// 从枚举中获取Description
        /// </summary>
        /// <param name="enumName">需要获取枚举描述的枚举<</param>
        /// <returns>描述内容</returns>
        public static string GetDescription(this Enum enumName)
        {
            string description = string.Empty;
            FieldInfo fieldInfo = enumName.GetType().GetField(enumName.ToString());
            DescriptionAttribute[] attributes = fieldInfo.GetDescriptAttr();
            if (attributes != null && attributes.Length > 0)
                description = attributes[0].Description;
            else
                description = enumName.ToString();
            return description;
        }  

        /// <summary>
        /// 将枚举转换为ArrayList
        /// 说明：若不是枚举类型，则返回NULL
        /// </summary>
        /// <param name="type">枚举类型</param>
        /// <returns>枚举描述字典</returns>
        public static Dictionary<int, string> ToDictionary(this Type type)
        {
            if (type.IsEnum)
            {
                Dictionary<int, string> dic = new Dictionary<int, string>();
                Array enumValues = Enum.GetValues(type);
                foreach (Enum value in enumValues)
                {
                    dic[value.GetHashCode()] = GetDescription(value);
                }
                return dic;
            }
            return null;
        }  


    }
}
